using System;
using System.Windows.Controls;
using System.Windows.Input;
using System.ComponentModel;
using System.Windows;

namespace Toon.Controls
{
	public class ImprovedChildWindow : ChildWindow
	{
		private Control m_Owner;
		private bool m_IsOpen;

        protected override void OnKeyUp(KeyEventArgs e)
		{
			base.OnKeyUp(e);
			if (!e.Handled)
				if (e.Key == Key.Escape)
				{
					e.Handled = true;

					DialogResult = false;

				}
		}

		private void Overlay_Click(object sender, MouseButtonEventArgs e)
		{
			DialogResult = false;
		}

		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();
			var overlay = (Grid)GetTemplateChild("Overlay");

			System.Threading.ThreadPool.QueueUserWorkItem((S) =>
			{
				System.Threading.Thread.Sleep(500);
				Dispatcher.BeginInvoke(() =>
				{
					overlay.MouseLeftButtonUp += Overlay_Click;
					overlay.MouseRightButtonUp += Overlay_Click;
				});
			});

		}

		/// <summary>
		/// Shows the ChildWindow. If the owner is unloaded, this is closed.
		/// </summary>
		/// <param name="owner"></param>
		public void Show(Control owner)
		{
			if (owner != null)
			{
				m_Owner = owner;
				m_Owner.Unloaded += Owner_Unloaded;
			}
			
            Show();
		}

		protected override void OnClosing(CancelEventArgs e)
		{
			if (m_Owner != null)
				m_Owner.Unloaded -= Owner_Unloaded;
			base.OnClosing(e);
		}

		protected override void OnClosed(EventArgs e)
		{
			base.OnClosed(e);
			m_IsOpen = false;
		}

		protected override void OnOpened()
		{
			base.OnOpened();
			m_IsOpen = true;
		}

		void Owner_Unloaded(object sender, RoutedEventArgs e)
		{
			Close();
		}

		public bool IsOpen
		{
			get { return m_IsOpen; }
		}
	}
}
